package com.sanley.coronavirus.common.security;

import com.alibaba.fastjson2.JSON;
import com.sanley.coronavirus.common.api.CommonResult;
import com.sanley.coronavirus.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author: ming
 * @create: 2022-10-14 21:07
 * @program: coronavirus
 */
@Service("authenticationSuccessHandler")
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response

            , Authentication authentication) throws IOException {

        logger.info("User: " + request.getParameter("username") + " Login successfully.");

        this.returnJson(response, authentication);

    }

    private void returnJson(HttpServletResponse response, Authentication authentication) throws IOException {


        String token = jwtUtils.generateToken((UserDetails) authentication.getPrincipal());

        response.setStatus(HttpServletResponse.SC_OK);

        response.setCharacterEncoding("UTF-8");

        response.setContentType("application/json");
        HashMap<String, Object> map = new HashMap<>();
        map.put("authKey", "Authorization");
        map.put("token", token);
        response.getWriter().print(JSON.toJSONString(CommonResult.success(map, "登陆成功")));
    }

}
